#include <cstdio>
#include <cstdlib>
#include <ctime>

typedef struct Node {
    int data;
    struct Node *next;
} Node;

Node *initList(){
    Node *list = (Node *)malloc(sizeof(Node));
    list->data = 0;
    list->next = list;
    return list;
}
void headInsert(Node *list, int val) {
    if(list == nullptr) return ;
    Node *node = (Node *)malloc(sizeof(Node));
    node->data = val;
    node->next = list->next;
    list->next = node;
    list->data++;
    return ;
}
void tailInsert(Node *list, int val) {
    if(list == nullptr) return ;
    Node *node = (Node *)malloc(sizeof(Node));
    node->data = val;
    Node *current = list;   // 注意
    while(current->next != list) {
        current = current->next;
    }
    node->next = list;
    current->next = node;
    list->data++;
}
bool deleteElement(Node *list, int val) {
    if(list == nullptr) return false;
    Node *pre = list;
    Node *current = list->next;
    while (current != list) {
        if (current->data == val) {
            pre->next = current->next;
            free(current);
            list->data--;
            return true;
        }
        pre = current;
        current = current->next;
    }
    return false;
}
void printList(Node *list) {
    if(list == nullptr) return ;
    Node *current = list->next;
    while(current != list) {
        printf("%3d ->", current->data);
        current = current->next;
    }
    printf(" loop\n\n");
}

int main() {
    srand(time(0));
    Node *list = initList();
    for(int i = 0; i < 5; i++) {
        headInsert(list, i + 1);
    }
    printList(list);
    for(int i = 0; i < 5; i++) {
        tailInsert(list, i + 10);
    }
    printList(list);
    deleteElement(list, 5);
    deleteElement(list, 2);
    printList(list);
    return 0;
}